"use client";

import axios from "axios";
import { useState } from "react";

interface WeatherInfo {
  code: number;
  msg: string;
  data: {
    type: string;
    lives: [
      {
        province: string;
        city: string;
        adcode: string;
        weather: string;
        temperature: string;
        winddirection: string;
        windpower: string;
        humidity: string;
        reporttime: string;
        temperature_float: string;
        humidity_float: string;
      }
    ];
    forecasts: any[];
    countMsg: string;
    tips: string;
  };
}

export default function Main() {
  const [address, setAddress] = useState("");
  const [weatherInfo, setWeatherInfo] = useState<WeatherInfo | null>(null);
  const [error, setError] = useState("");

  const fetchWeatherInfo = async () => {
    try {
      const response = await axios.get(
        `http://127.0.0.1:5000/weather?address=${address}`
      );
      setWeatherInfo(response.data);
    } catch (err: any) {
      const errorMessage = err.response
        ? err.response.data.error
        : "Failed to fetch weather information";
      setError(errorMessage);
    }
  };
  return (
    <main className="grow ">
      <div className="mx-32">
        <div className=" ">
          <label htmlFor="address" className="mr-2">
            Address:
          </label>
          <input
            type="text"
            value={address}
            onChange={(e) => setAddress(e.target.value)}
            className="border-2 border-gray-300 rounded-md px-4 py-2 w-36"
          />
          <button
            onClick={fetchWeatherInfo}
            className="ml-2 bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded"
          >
            Get Weather
          </button>
        </div>
        {error && <div>{error}</div>}
        {weatherInfo && (
          <div className="bg-slate-200 mt-10 p-4">
            <p>省份: {weatherInfo.data.lives[0].province}</p>
            <p>城市: {weatherInfo.data.lives[0].city}</p>
            <p>天气: {weatherInfo.data.lives[0].weather}</p>
            <p>温度: {weatherInfo.data.lives[0].temperature}</p>
            <p>风向: {weatherInfo.data.lives[0].winddirection}</p>
            <p>风力: {weatherInfo.data.lives[0].windpower}</p>
            <p>湿度: {weatherInfo.data.lives[0].humidity}</p>
          </div>
        )}
      </div>
    </main>
  );
}
